package controllers

import (
	"fmt"
	"log"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type UploadController struct {
	bucket *oss.Bucket
}

const (
	OSS_ENDPOINT          = "oss-cn-guangzhou.aliyuncs.com"
	OSS_BUCKET            = "duyu-public-test"
	OSS_ACCESS_KEY_ID     = "LTAIFLIjTL1ZomIf"
	OSS_ACCESS_KEY_SECRET = "OjsSaUo1uCcrH8YmFTUl6yfxUNaxXC"
)

func NewUploadController() *UploadController {
	client, err := oss.New(OSS_ENDPOINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
	fmt.Println(client)
	if err != nil {
		log.Fatalf("OSS client initialization 失败: %v", err)
		return nil
	}

	bucket, err := client.Bucket(OSS_BUCKET)
	if err != nil {
		log.Fatalf("OSS bucket initialization 失败: %v", err)
		return nil
	}

	return &UploadController{bucket: bucket}
}

func (ctrl *UploadController) UploadImage(c *gin.Context) {
	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		log.Printf("获取文件失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "未找到文件或文件格式错误"})
		return
	}

	// 检查文件大小（例如限制为10MB）
	if file.Size > 10*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件大小超过10MB限制"})
		return
	}

	// 检查文件类型
	ext := strings.ToLower(filepath.Ext(file.Filename))
	allowedExts := map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
		".gif":  true,
		".webp": true,
	}

	if !allowedExts[ext] {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的文件类型，仅支持 jpg, jpeg, png, gif, webp"})
		return
	}

	// 打开上传的文件
	src, err := file.Open()
	if err != nil {
		log.Printf("打开文件失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "文件处理失败"})
		return
	}
	defer src.Close()

	// 生成唯一文件名
	customFileName := generateFileName(file.Filename)

	// 上传文件到OSS (使用正确的方法)
	err = ctrl.bucket.PutObject(customFileName, src)
	if err != nil {
		log.Printf("OSS上传失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "上传到OSS失败"})
		return
	}

	// 构建OSS访问链接
	ossLink := fmt.Sprintf("https://%s.%s/%s", OSS_BUCKET, OSS_ENDPOINT, customFileName)

	log.Printf("文件上传成功: %s", ossLink)

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"message":  "上传成功",
		"url":      ossLink,
		"filename": customFileName,
		"size":     file.Size,
	})
}

// 生成唯一文件名
func generateFileName(originalName string) string {
	ext := filepath.Ext(originalName)
	timestamp := time.Now().Format("20060102150405")
	uuid := uuid.New().String()[:8]

	return fmt.Sprintf("leyou_%s_%s%s", timestamp, uuid, ext)
}

// 批量上传方法
func (ctrl *UploadController) UploadMultipleImages(c *gin.Context) {
	form, err := c.MultipartForm()

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "解析表单失败"})
		return
	}

	files := form.File["files"] // 注意这里是"files"
	if len(files) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "未找到文件"})
		return
	}

	var results []map[string]interface{}
	var errors []string

	for _, file := range files {
		src, err := file.Open()
		if err != nil {
			errors = append(errors, fmt.Sprintf("文件 %s 打开失败: %v", file.Filename, err))
			continue
		}

		customFileName := generateFileName(file.Filename)

		err = ctrl.bucket.PutObject(customFileName, src)
		src.Close()

		if err != nil {
			errors = append(errors, fmt.Sprintf("文件 %s 上传失败: %v", file.Filename, err))
			continue
		}

		ossLink := fmt.Sprintf("https://%s.%s/%s", OSS_BUCKET, OSS_ENDPOINT, customFileName)

		results = append(results, map[string]interface{}{
			"original_name": file.Filename,
			"filename":      customFileName,
			"url":           ossLink,
			"size":          file.Size,
		})
	}

	response := gin.H{
		"message": "批量上传完成",
		"success": results,
	}

	if len(errors) > 0 {
		response["errors"] = errors
	}

	c.JSON(http.StatusOK, response)
}
